#include <iostream>
#include <unistd.h>
#include <pthread.h>

int count1 = 100;
pthread_mutex_t mymutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t mycond1=PTHREAD_COND_INITIALIZER;

void *thread1(void *argv)
{
    while (1)
    {
        pthread_mutex_lock(&mymutex1);
        pthread_cond_wait(&mycond1,&mymutex1);
        if (count1 > 0)
        {
            std::cout << "child thread tid: " << (char *)argv << " my count = " << count1 << std::endl;
            count1--;
            pthread_mutex_unlock(&mymutex1);
        }
        else
        {
            pthread_mutex_unlock(&mymutex1);
            return nullptr;
        }
    }
    return nullptr;
}

// linux加锁
void linux_mutex()
{
    pthread_t pth1_id;
    int pth1_ret = pthread_create(&pth1_id, NULL, thread1, (void *)"thread1_name");
    pthread_t pth2_id;
    int pth2_ret = pthread_create(&pth2_id, NULL, thread1, (void *)"thread2_name");
    pthread_t pth3_id;
    int pth3_ret = pthread_create(&pth3_id, NULL, thread1, (void *)"thread3_name");
    pthread_t pth4_id;
    int pth4_ret = pthread_create(&pth4_id, NULL, thread1, (void *)"thread4_name");
    pthread_t pth5_id;
    int pth5_ret = pthread_create(&pth5_id, NULL, thread1, (void *)"thread5_name");

    pthread_detach(pth1_id);
    pthread_detach(pth2_id);
    pthread_detach(pth3_id);
    pthread_detach(pth4_id);
    pthread_detach(pth5_id);

    while (count1 > 0)
    {
        usleep(1);
        //pthread_cond_broadcast(&mycond1);
        pthread_cond_signal(&mycond1);
    }
    usleep(2000);
}

int main()
{
    linux_mutex();
    return 0;
}

